
/**
 * 春季续班-中心维度续班看板
 * @author wl
 */
import React, {useRef, useState, useEffect, createRef} from 'react';
import {Card, Button, Modal, Row, Col} from 'antd';
import CommonSearchBar from '~/page/FineBi/common/CommonSearchBar';
import CommonTitle from '~/page/FineBi/common/Title';
import {convertSearcherParams} from '~/page/FineBi/utils/convert';
import DataText from '~/page/FineBi/common/DataText';
import Carousel from '~/page/FineBi/common/Carousel';
import UserRoundTabs from '~/page/FineBi/common/UserRoundTabs';
import {userRoundIdx, initUserRoundIdx} from '~/utils/const';

import {
    querySelectOptions,
} from '~/service/refundReport';
import DataCard from './comps/DataCard';
import CentralGeneralTable from './comps/CentralGeneralTable';
import StructureBarAndTableConfig from './comps/StructureBarAndTableConfig';
import {splitFormValues} from './utils';

import {
    partConfig, cardsConfig, selectDId1, selectDId2, selectDId3, selectDId4, selectDId5,
    selectDIdTitle, searchTitleConfig, searchTitleInitival
} from './config';
import './index.less';

export const initDimensionAndValues = [
    {
        dimensionId: `Center_Dimension_Title_select_${userRoundIdx}`,
        dimensionName: userRoundIdx,
        // 一轮班 1 二轮班 2
        value: [initUserRoundIdx]
    }
];

const initDimensionValues = {
    [selectDIdTitle]: initDimensionAndValues,
    [selectDId1]: initDimensionAndValues,
    [selectDId2]: initDimensionAndValues,
    [selectDId3]: initDimensionAndValues,
    [selectDId4]: initDimensionAndValues,
    [selectDId5]: initDimensionAndValues,
};

const CentralXubanReport = props => {
    const formRefConfig = useRef({});
    /* eslint-disable */
    // 重新进页面，不会重新初始化，所以改变默认值地址
    const dimensionAndValuesRef = useRef({...initDimensionValues});
    const [selectOptions, setSelectOptions] = useState({});
    const [loading, setLoading] = useState(false);
    const [refresh, setRefresh] = useState(false);
    const [userRoundValue, setUserRoundValue] = useState(initUserRoundIdx);

    const handleOk = selectDId => fieldsValue => {
        if (selectDId === selectDIdTitle) {
            let dimension = convertSearcherParams(fieldsValue);
            dimension = dimension.map(ele => ({
                ...ele,
                dimensionId: `${selectDIdTitle}_${ele.dimensionName}`,
            }));
            dimensionAndValuesRef.current[selectDId] = [...dimension, {...initDimensionAndValues[0], value: [userRoundValue]}];
        }
        else {
            // 该看板的search-key用 unitId 做了区分，需要转成正常的key
            const {newFieldsValue} = splitFormValues(fieldsValue);
            const params = convertSearcherParams(newFieldsValue);
            dimensionAndValuesRef.current[selectDId] = [...params, {...initDimensionAndValues[0], value: [userRoundValue]}];
        }

        setRefresh(!refresh);
    };

    const handleReset = selectDId => () => {
        dimensionAndValuesRef.current[selectDId] = [{...initDimensionAndValues[0], value: [userRoundValue]}];

        setRefresh(!refresh);
    };

    // 选项查询
    const handleFetchOptions = selectDId => options => {
        const {
            key, searchKey, dimensionName, pager, isGetingMore, options: curOptions, fieldsValue, optionsConfig
        } = options;
        let permissions = [];
        let params = {};
        if (selectDId === selectDIdTitle) {
            permissions = searchTitleConfig.map(item => ({
                dimensionId: `${selectDIdTitle}_${item.key}`,
                dimensionName: item.key,
                filterItems: Array.isArray(fieldsValue[item.key])
                    ? fieldsValue[item.key]
                    : fieldsValue[item.key] == null
                        ? []
                        : [fieldsValue[item.key]]
            }));
            params = {
                pager,
                dimensionId: `${selectDIdTitle}_${key}`,
                dimensionName: key,
                searchKey,
                permissions,
                unitId: selectDIdTitle
            };
        }
        else {
            const {searchConfig} = partConfig.find(item => key.includes(item.selectDId));

            permissions = searchConfig.map(item => ({
                dimensionId: item.optionsConfig.dId,
                dimensionName: item.dimensionName,
                filterItems: Array.isArray(fieldsValue[item.key])
                    ? fieldsValue[item.key]
                    : fieldsValue[item.key] == null
                        ? []
                        : [fieldsValue[item.key]]
            }));
            params = {
                pager,
                dimensionId: `${optionsConfig.unitId}_${dimensionName}`,
                dimensionName,
                searchKey,
                permissions,
                unitId: optionsConfig.unitId
            };
        }

        permissions = permissions.filter(item => (item.filterItems?.length && item.dimensionName !== userRoundIdx));
        permissions.push({...initDimensionAndValues[0], value: [userRoundValue]});
        params.permissions = permissions;

        // 期的接口和其他的不同
        const fetchFn = querySelectOptions;

        return fetchFn(params).then(res => {
            const {data, pager} = res;
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});

            return (data || []);
        });
    };

    const handleItemChange = selectDId => formItem => {
        const form = formRefConfig.current[selectDId]?.formFields;
        const prop = Object.keys(formItem)[0];
        const values = formItem[prop];
        const newValues = values.filter(item => item !== '全部');

        form.setFieldsValue({[prop]: newValues});
    };

    const renderPartChilds = part => {
        if (part.children && part.type !== 'echarAndTable') {
            return (
                part.children.map(child => (
                    renderPartChilds(child)
                ))
            );
        }

        const {id: dId, unitId, selectDId} = part;
        const dimensionAndValues = dimensionAndValuesRef?.current?.[selectDId];
        const configProps = {
            ...part,
            dId,
            // 此处的unitid 是为了拿titlename。具体取组件的数据时，根据children里的unitid
            unitId: unitId || part?.children[0].unitId,
            dimensionAndValues
        };

        return (
            <Col span={part.span || 24}>
                <StructureBarAndTableConfig
                    {...configProps}
                    fetchData={part.ajax}
                    userRoundValue={userRoundValue}
                />
            </Col>
        );
    };

    const handleCreateRef = id => ele => {
        formRefConfig.current[id] = ele;
    };

    const handleRadioChange = e => {
        const {value} = e.target;
        setUserRoundValue(value);

        const selectDIds = Object.keys(dimensionAndValuesRef.current);
        selectDIds.forEach(selectDId => {
            // 清空下拉框
            const form = formRefConfig.current[selectDId]?.formFields;
            form.resetFields();

            // 刷新参数
            dimensionAndValuesRef.current[selectDId] = [{...initDimensionValues[selectDId][0], value: [value]}];
        });

        setRefresh(!refresh);
    };

    return (
        <div className="center-xuban">
            <Carousel />
            <CommonTitle
                title="中心维度续班看板"
                iconDom={(
                    <UserRoundTabs
                        onRadioChange={handleRadioChange}
                    />
                )}
            />
            <Card bordered={false}>
                <DataText
                    dId="Center_Dimension_Title"
                    unitId="Center_Dimension_Title_text"
                />
            </Card>
            <Card bordered={false} style={{marginTop: '24px', marginBottom: '8px'}}>
                <CommonSearchBar
                    noCache
                    config={searchTitleConfig}
                    initialValues={searchTitleInitival}
                    onOk={handleOk(selectDIdTitle)}
                    onReset={handleReset(selectDIdTitle)}
                    onfetchOptions={handleFetchOptions(selectDIdTitle)}
                    onItemChange={handleItemChange(selectDIdTitle)}
                    selectOptions={selectOptions}
                    ref={handleCreateRef(selectDIdTitle)}
                />
            </Card>
            <Card bordered={false}>
                <Row>
                    {cardsConfig.map(card => (
                        <Col key={card.id} span={8}>
                            <DataCard
                                dId={card.id}
                                dimensionAndValues={dimensionAndValuesRef?.current?.[selectDIdTitle]}
                                unitId={card.unitId}
                                isRatio={card.isRatio}
                            />
                        </Col>
                    ))}
                </Row>
                <CentralGeneralTable
                    dId="Center_Dimension_partTwo_Center_Basic"
                    unitId="Center_Dimension_partTwo_Center_Basic_excel"
                    // dimensionAndValues={generalTableDimension}
                    dimensionAndValues={dimensionAndValuesRef?.current?.[selectDIdTitle]}
                    userRoundValue={userRoundValue}
                />
            </Card>
            {partConfig.map(part => (
                <div
                    key={part.id}
                >
                    {part.searchConfig && (
                        <Card bordered={false} style={{marginTop: '24px', marginBottom: '8px'}}>
                            <CommonSearchBar
                                noCache
                                config={part.searchConfig}
                                initialValues={part.initialValues}
                                onOk={handleOk(part.selectDId)}
                                onReset={handleReset(part.selectDId)}
                                onfetchOptions={handleFetchOptions(part.selectDId)}
                                onItemChange={handleItemChange(part.selectDId)}
                                selectOptions={selectOptions}
                                ref={handleCreateRef(part.selectDId)}
                            />
                        </Card>
                    )}
                    <Card bordered={false}>
                        <Row>
                            {renderPartChilds(part)}
                        </Row>
                    </Card>
                </div>
            ))}
        </div>
    );
};

export default CentralXubanReport;
